define(function (require, exports) {
	var $ = require('jquery');
	var pubjs = require('pubjs');
	var util = require('util');
	var view = require('@base/view');
	var dspUtil = require('dspUtil');

	// raido值定义
	var RAIDO_VALUE_DEFINE = pubjs.config('RAIDO_VALUE_DEFINE');

	// 定向配置
	var DATA = {
		// 媒体定向
		'media': [
			{'name': LANG('渠道'), 'id':'Adx', 'right': pubjs.checkRight('')},
			{'name': LANG('媒体广告位'), 'id':'MediaSpot', 'right': pubjs.checkRight('')},
			{'name': LANG('订单广告位'), 'id':'DealSpot', 'right': pubjs.checkRight('')},
			// {'name': LANG('媒体分类'), 'id':'Category', 'right': pubjs.checkRight('')},
			// {'name': LANG('视频定向'), 'id':'VideoDirect', 'right': pubjs.checkRight('')},
			{'name': LANG('展现形式'), 'id':'ViewType', 'right': pubjs.checkRight('')},
			{'name': LANG('屏次'), 'id':'Screen', 'right': pubjs.checkRight('')}
		],
		// 人群定向
		'people': [
			// {'name': LANG('自有人群'), 'id':'BdxPeople', 'right': pubjs.checkRight('')},
			{'name': LANG('WEB重定向'), 'id':'Character', 'right': pubjs.checkRight('')},
			{'name': LANG('APP重定向'), 'id':'APP_Character', 'right': pubjs.checkRight('')}
		],

		// 环境定向
		'environment': [
			{'name': LANG('地区'), 'id':'Zone', 'right': pubjs.checkRight('')},
			//{'name': LANG('投放时间'), 'id':'Time', 'right': pubjs.checkRight('')},
			{'name': LANG('投放时段'), 'id':'TimeSet', 'right': pubjs.checkRight('')},
			{'name': LANG('移动网络类型'), 'id':'APP_Network', 'right': pubjs.checkRight('')},
			{'name': LANG('网络运营商'), 'id':'APP_Carriers', 'right': pubjs.checkRight('')}

		],

		// 设备定向
		'device': [
			{'name': LANG('IP地址段'), 'id':'IpSections', 'right': pubjs.checkRight('')},
			{'name': LANG('APP设备'), 'id':'APP_DeviceType', 'right': pubjs.checkRight('')},
			{'name': LANG('APP操作系统'), 'id':'APP_OSType', 'right': pubjs.checkRight('')},
			{'name': LANG('WEB客户端'), 'id':'Client', 'right': pubjs.checkRight('')}

		]
	}


	// 主模块
	var Base = view.container.extend({
		init: function(config) {
			var rvd = RAIDO_VALUE_DEFINE;

			config = pubjs.conf(config, {
				'class': 'P-campaignBasic',
				'tplFile': '/tpl/campaign/editStep/orient.tpl',
				'modules': ['media', 'people', 'environment', 'device'],
				'hasImport': true,
				'vModel': {

					'_mediaRadio': rvd.ALL,
					'_peopleRadio': rvd.ALL,
					'_environmentRadio': rvd.ALL,
					'_deviceRadio': rvd.ALL,

					'hasImport': true,
					'hasSectionTitle': true,

					'vmClickSelectOrient': this.eventClickSelectOrient
				},
				'url': {
				}
			});
			this.Super('init', arguments);
		},
		afterBuild: function() {
			var self = this;
			var c = self.getConfig();
			self.getDOM().addClass(c.class);

			self.vm.$.hasImport = c.hasImport;

			var opts = {
				'media': {},
				'people': {},
				'environment': {},
				'device': {}
			};

			self.buildFromTemplate(util.extend(opts, c.tipOpts));
		},
		beforeBuildTemplate: function(){

		},
		afterBuildTemplate: function(){

		},
		// 导入定向策略
		eventClickSelectOrient: function(ev){
			var self = this;
			var pop = self.get('selectCondition');

			if(!pop){
				self.createAsync('selectCondition', 'campaign/popwin/selectCondition.main', {

				}, function(mod){
					if(mod){
						mod.show();
					}
				});
			}else{
				pop.show();
			}
		},
		// 导入定向策略回调
		onSelectConditionSuccess: function(ev){
			this.reset();
			this.setData({MainCondition: ev.param});
		},
		onHasCondition: function(ev){
			var rvd = RAIDO_VALUE_DEFINE;   // raido值定义常量
			if(ev && ev.param && ev.param.length){
				this.vm.$['_'+ev.name+'Radio'] = rvd.NOT_ALL;
			}
			return false;
		},
		validate: function(data){
			var self = this;
			data = data || self.getData();
			if (data) {

			}

			return true;
		},
		setData: function(data){
			var self = this;
			var cs = self.$;
			var c = self.getConfig();
			var MainCondition = data.MainCondition;
			self.$MainConditionId = data.MainConditionId || null;

			util.each(c.modules, function(item){
				if(self.get(item)){
					cs[item].setData(MainCondition.Data);
				}
			});

			return self;
		},
		getData: function(){
			var self = this;
			var vm = self.vm.$;
			var cs = self.$;
			var c = self.getConfig();
			var data = {};
			var items = [];

			util.each(c.modules, function(item){
				if(self.get(item) && vm['_'+item+'Radio'] != RAIDO_VALUE_DEFINE.ALL){
					var modData = cs[item].getData();
					items = items.concat(modData.Items || []);
				}
			});

			data.MainCondition = {
				Desc: '',
				Data: {
					Items: items,
					Operator: 1
				}
			};
			if(self.$MainConditionId){
				data.MainConditionId = self.$MainConditionId;
			}

			return data;
		},
		reset: function(){
			var self = this;
			var c = self.getConfig();
			self.$MainConditionId = null;
			self.vm.reset();

			self.vm.$.hasImport = c.hasImport;
			self.resetCondition();
			util.each(c.modules, function(item){
				if(self.get(item)){
					self.get(item).reset();
				}
			});

			return self;
		},
		resetCondition: function(){
			var el = this.getDOM();
			el.find('.conditionCon').removeClass('dn');
			return this;
		},
		onLoadPlanData: function(data){
			var self = this;
			var el = self.getDOM();
			var clients = +data.param.Clients;
			self.resetCondition();
			//推广组类型为移动APP和移动WAP时
			var appRel = ['APP_Network', 'APP_DeviceType', 'APP_OSType'];

			switch (clients){
				case 1:
					util.each(appRel, function(item){
						el.find('label[data-id="'+item+'"]').parent().addClass('dn');
					});
					break;
				case 2:
				case 3:
					el.find("label[data-id = 'Client']").parent().addClass('dn');
					break;
			}
		},
		onChangeBidType: function(ev){
			var self = this;
			var el = self.getDOM();
			el.find("label[data-id = 'DealSpot']").parent().toggleClass('dn', !+ev.param);
		}
	});
	exports.base = Base;

	// 管理中心-定向策略
	var Edit = Base.extend({
		init: function(config) {
			var rvd = RAIDO_VALUE_DEFINE;

			config = pubjs.conf(config, {
				'class': 'P-campaignBasic',
				'hasImport': false,
				'tplFile': '/tpl/campaign/editStep/orient.tpl',
				'vModel': {

					'_mediaRadio': rvd.ALL,
					'_peopleRadio': rvd.ALL,
					'_environmentRadio': rvd.ALL,
					'_deviceRadio': rvd.ALL,

					'hasImport': false,
					'hasSectionTitle': false,

					'name': '',

					'vmClickSelectOrient': this.eventClickSelectOrient

				},
				'url': {
					'info': 'condition/info',
					'add': 'condition/add',
					'update': 'condition/update'
				}
			});

			this.Super('init', arguments);
		},
		afterBuild: function() {
			var self = this;
			var c = self.getConfig();
			var vm = this.vm;
			var el = self.getDOM();

			el.addClass(c.class);

			self.vm.$.hasImport = c.hasImport;

			$([
				'<div class="M-formConGroup P-adsAddChannelCon">',
					'<label class="M-formLabel group-label">'+LANG('广告主：')+'</label>',
					'<div class="group-content">',
						'<span pub-name="advertiser" pub-mod="@base/common/drop.drop"/>',
					'</div>',
				'</div>',
				'<div class="M-formConGroup P-adsAddChannelCon">',
					'<label class="M-formLabel group-label">'+LANG('定向策略名称：')+'</label>',
					'<div class="group-content">',
						'<input  placeholder="'+LANG('不超过50个字符')+'" v-model="name" type="text" class="w300"/>',
					'</div>',
				'</div>'
			].join('')).appendTo(el.find('.createCon'));


			$([
				'<div class="M-formButtons">',
					'<span pub-name="cancel" pub-mod="@base/common/input.button" class="mr10" />',
					'<span pub-name="save" pub-mod="@base/common/input.button" />',
				'</div>',
			].join('')).appendTo(el);


			vm.mount();

			var opts = {
				'advertiser': {
					'type': 'button',
					'url': 'qualification/owns',
					'name': 'Name',
					'key': '_id',
					'reqType': 'websocket',
					'all': true,
					'width': 300,
					// 'def': '',
					'param': {

					},
					'def': LANG('选择广告主'),
					'panel_config': {
						'hasSearch': true,
						'height': 200
					}
				},
				'cancel': {
					value: LANG('取消'),
					class: 'btn btn-link mr10 mt10'
				},
				'save': {
					value: LANG('保存'),
					class: 'btn btn-confirm mt10'
				},
				'media': {},
				'people': {},
				'environment': {},
				'device': {}
			};

			self.buildFromTemplate(util.extend(opts, c.tipOpts));
		},
		onInputClick: function(ev){
			switch (ev.name){
				case 'save':
					return this.save();
				case 'cancel':
					return this.cancel();
			}
			return false;
		},
		load: function(id, isCopy) {
			var self = this;
			var vm = self.vm;
			var c = self.getConfig();
			if(id){
				if(!isCopy){
					self.$isEdit = true;
					self.$id = +id;
				}
			}
			vm.set('_id',+id);

			self.showLoading();
			pubjs.mc.send(c.url.info, {_id: +id}, self.onData.bind(self), isCopy);
			return self;
		},
		onData: function(err, data, isCopy) {
			this.hideLoading();
			if(err) {
				return pubjs.alert(err.message);
			}

			this.$id = data._id;
			this.setData(data);
		},
		setData: function(data) {
			var self = this;
			var cs = self.$;
			var c = self.getConfig();

			self.vm.$.name = data.Name;

			self.$.advertiser.setValue(data.AdvertiserId);

			util.each(c.modules, function(item){
				if(self.get(item)){
					cs[item].setData(data.Data);
				}
			});

			return self;
		},
		getData: function(){
			var self = this;
			var vm = self.vm.$;
			var cs = self.$;
			var c = self.getConfig();
			var items = [];

			util.each(c.modules, function(item){
				if(self.get(item) && vm['_'+item+'Radio'] != RAIDO_VALUE_DEFINE.ALL){
					var modData = cs[item].getData();
					items = items.concat(modData.Items || []);
				}
			});

			var data = {
				AdvertiserId: +cs.advertiser.getValue(true).id || 0,
				Name: util.trim(vm.name),
				Desc: LANG('定向描述'),
				Data: {
					Items: items,
					Operator: 1
				}
			};

			return data;
		},
		cancel: function(){
			pubjs.controller.navigate('admin/orientation');
		},
		validate: function(data){

			if(!data.AdvertiserId){
				// pubjs.alert(LANG('请选择广告主'));
				// return false;
			}

			if(!data.Name){
				pubjs.alert(LANG('请填写定向策略名称'));
				return false;
			}

			if(!data.Data.Items.length){
				pubjs.alert(LANG('请至少需设置一个定向条件'));
				return false;
			}

			return true;
		},
		save: function(){
			var url;
			var self = this;
			var data = self.getData();
			var c = self.getConfig('url');

			if(self.validate(data)){
				if(self.$isEdit && self.$id){
					data._id = self.$id;
				}
				if(data._id){
					url = c.update;
				}else{
					url = c.add;
				}
				self.showLoading();
				pubjs.mc.send(url, data, self.afterSave.bind(self));
			}
		},
		afterSave: function(err, data){
			this.hideLoading();
			if (err) {
				pubjs.alert(err.message);
				return false;
			}
			this.cancel();
		},
		reset: function(){
			var self = this;
			var c = self.getConfig();
			self.vm.reset();
			self.$id = null;

			self.$.advertiser.reset().load();

			util.each(c.modules, function(item){
				if(self.get(item)){
					self.get(item).reset();
				}
			});

			return self;
		}
	});
	exports.edit = Edit;


	// 媒体定向
	var Media = view.container.extend({
		init: function(config) {
			config = pubjs.conf(config, {
				'class': 'P-campaignOrientMedia',
				'type': 'media',
				'set_text': LANG('设置'),
				'vModel': {
					'data': [], // 循环数据
					'condition': [] // 已选的条件名称数组

				},
				'url': {
				}
			});

			this.$cacheData = {}; // 缓存数据
			this.$map = {}; // 拥有的选项

			this.Super('init', arguments);
		},
		afterBuild: function() {
			var self = this;
			var c = self.getConfig();
			var vm = self.vm.$;
			var el = self.getDOM();

			el.addClass(c.class);

			vm.data = DATA[c.type];

			util.each(DATA[c.type], function(item){
				self.$map[item.id] = 1;
			});

			$([
				'<div>',
					'<div class="conditionCon" v-for="item of data" v-show="item.right">',
						'<label class="" v-bind:data-id="item.id" v-if="item.right">',
							'<input type="checkbox" class="valign-m mr5" v-model="condition"  v-bind:value="item.id" v-bind:data-id="item.id" v-bind:data-index="$index"/>',
							'<span class="valign-m" v-bind:data-id="item.id" v-bind:data-text="item.name">{{item.name}}</span>',
						'</label>',
						'<a class="set link text-truncate" v-if="item.right" v-bind:data-id="item.id" v-bind:data-text="item.name" >'+c.set_text+'</a>',
					'</div>',
				'</div>'
			].join('')).appendTo(el);

			self.vm.mount();

			self.uiProxy(el, '.conditionCon label input', 'change', 'eventToggleCondition');

			self.uiProxy(el, '.conditionCon .set', 'click', 'eventClickAddCond');

			// 子条件选项设置弹窗
			self.createAsync('settingsPop', 'promotion/popwin/settings.main');

			// self.buildFromTemplate({});
		},
		// 开关条件
		eventToggleCondition: function(evt, elm){
			var checked = $(elm).attr('checked');
			var index = $(elm).attr('data-index');
			this.vm.$.data[index].checked = checked;
			var a = $(elm).parent().next('a').toggleClass('dib', checked);
			if($(elm).attr("checked")){
				this.eventClickAddCond(evt,a);
			}

		},
		eventClickAddCond: function(evt, elm){
			var id = $(elm).attr('data-id');
			var title = $(elm).attr('data-text');
			var data = this.$cacheData[id];

			this.$.settingsPop.reset().show()
				.setTitle(title).setType(id)
				.setAnchor($(elm)).setEdit(false);

			// 如果有缓存数据，设置值
			if(data){
				this.$.settingsPop.setData(data);
			}
		},
		afterBuildTemplate: function(){

		},
		validate: function(){
			var self = this;
			data = data || self.getData();
			if (data) {

			}

			return true;
		},
		setData: function(data){
			var self = this;
			var el = self.getDOM();
			if(data && data.Items){

				var condition = [];
				util.each(data.Items, function(item){
					if(self.$map[item.Type]){
						condition.push(item.Type);
						self.renderDesc(item);
					}
				});

				self.vm.set('condition', condition);

				if(condition.length){
					self.fire('HasCondition', condition);
				}
			}

			return self;
		},
		getData: function(){
			var self = this;
			var el = self.getDOM();
			var cacheData = self.$cacheData;
			var condition = self.vm.get('condition');

			// 条件结构
			var data = {
				Operator: 1,
				Items: []
			};

			util.each(condition, function(item){
				// 判断不处在隐藏状态(必须是带dn样式名的)，才记录结果
				if(item && cacheData[item]){
					if(!el.find("label[data-id='"+item+"']").parent().hasClass('dn')){
						var obj = util.clone(cacheData[item]);
						delete obj.anchor;
						delete obj.IsEdit;
						data.Items.push(obj);
					}
				}
			});

			return data;
		},
		onSelectCondition: function(ev){
			// console.log(ev);
		},
		// 接受设置成功信息
		onSettingsSuccess: function(ev){
			this.renderDesc(ev.param);
			return false;
		},
		// 渲染描述
		renderDesc: function(data){
			var self = this;
			var el = self.getDOM();

			if(data){
				var desc = data.Desc;

				if(data.Relation == 2){
					title = LANG('排除') + desc;
				}else{
					title = LANG('已选') + desc;
				}

				el.find('.set[data-id="'+data.Type+'"]').text(title).attr('title', title).addClass('dib');

				this.$cacheData[data.Type] = data;
			}
		},
		reset: function(){
			var self = this;
			var c = self.getConfig();
			self.$cacheData = {};
			// self.vm.reset();
			self.vm.$.condition = [];
			self.getDOM().find('a.set').text(c.set_text).removeAttr('title').removeClass('dib');
			self.vm.mount();
			return self;
		}
	});
	exports.media = Media;

	// 人群定向
	var People = Media.extend({
		init: function(config) {
			config = pubjs.conf(config, {
				'class': 'P-campaignOrientMedia',
				'type': 'people',
				'vModel': {
					'data': [],

				},
				'url': {
				}
			});

			this.Super('init', arguments);
		},
	});
	exports.people = People;

	// 环境定向
	var Environment = Media.extend({
		init: function(config) {
			config = pubjs.conf(config, {
				'class': 'P-campaignOrientMedia',
				'type': 'environment',
				'vModel': {
					'data': [],

				},
				'url': {
				}
			});

			this.Super('init', arguments);
		},
	});
	exports.environment = Environment;

	// 设备定向
	var Device = Media.extend({
		init: function(config) {
			config = pubjs.conf(config, {
				'class': 'P-campaignOrientMedia',
				'type': 'device',
				'vModel': {
					'data': [],

				},
				'url': {
				}
			});

			this.Super('init', arguments);
		},
	});
	exports.device = Device;

});